package com.kitty.game.rank.service.handler;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.rank.model.RankType;
import com.kitty.game.rank.model.pojo.RankListData;
import com.kitty.game.rank.model.record.NewHelpRankRecord;
import com.kitty.game.rank.model.record.RankRecord;
import com.kitty.game.role.model.Role;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

/**新服助力活动排行榜处理类*/
@Component
@Slf4j
public class NewHelpRankHandler extends RankHandler {
    @Override
    public void init() {
        setRankSize(10);

        Dao dao = SpringUtils.getBean(Dao.class);
        RankListData rankListData = dao.fetch(RankListData.class, RankType.NEW_HELP.name());
        if (rankListData != null) {
            rankListData.doAfterInit();
            List<RankRecord> rankData = rankListData.getRankData();
            for (RankRecord rankRecord : rankData) {
                NewHelpRankRecord record = (NewHelpRankRecord)rankRecord;
                update(record.getGid(), record);
            }
        }
    }

    public void save() {
        List<RankRecord> records = getRecordsFrom(0, getRankSize());
        if (records == null || records.size() == 0) {return ;}

        List<RankRecord> rankRecords = new ArrayList<>(records.size());
        for (RankRecord rankRecord : records) {
            rankRecords.add(rankRecord);
        }

        if (rankRecords.size() <= 0) {return ;}

        RankListData rankListData = new RankListData(RankType.NEW_HELP, rankRecords);
        rankListData.doBeforeSave();

        Dao dao = SpringUtils.getBean(Dao.class);
        dao.insertOrUpdate(rankListData);
    }

    @PreDestroy
    private void shutDown() {
        save();
        log.error("[{}]保存数据后关闭", this.getClass().getSimpleName());
    }

    public void updateRank(Role role, int count) {
        NewHelpRankRecord bullyRankRecord = new NewHelpRankRecord(role.getGid(), role.getName(), count);
        update(bullyRankRecord.getGid(), bullyRankRecord);
    }
}
